package com.ysd.lis.controller.bac;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ysd.common.Result;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacBloodCultrue;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.request.bac.BloodCultureTransplantationParam;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bac.BacBloodCultrueService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.util.RedisUserManager;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 血培养结果记录 前端控制器
 * </p>
 *
 * @author cfz
 * @since 2024-08-21
 */
@RestController
@RequestMapping("/bac-blood-cultrue")
public class BacBloodCultrueController extends BaseController {
    @Autowired
    BacBloodCultrueService bacBloodCultrueService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    RedisSysParamHelper redisSysParamHelper;
    @Autowired
    LabMaininfoService labMaininfoService;

    @ApiOperation("查询")
    @GetMapping("/findBacBloodCultrueList")
    public Result findBacBloodCultrueList(BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.findBacBloodCultrueList(bacBloodCultrue);
    }

    @ApiOperation("危急值查询")
    @GetMapping("/getAlarmResult")
    public Result getAlarmResult(BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.getAlarmResult(bacBloodCultrue);
    }

    @ApiOperation("查询最后一条血培养数据")
    @GetMapping("/findLastoneBacBloodCultrueList")
    public Result findLastoneBacBloodCultrueList(BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.findLastoneBacBloodCultrueList(bacBloodCultrue);
    }

    @ApiOperation("查询血培养数据")
    @GetMapping("/findBacBloodCultrueByMaininfoList")
    public Result findBacBloodCultrueByMaininfoList(BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.findBacBloodCultrueByMaininfoList(bacBloodCultrue);
    }

    @ApiOperation("增加")
    @PostMapping("/addBacBloodCultrue")
    public Result addBacBloodCultrue(@RequestBody BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.addBacBloodCultrue(bacBloodCultrue);
    }

    @ApiOperation("删除")
    @PostMapping("/deleteBacBloodCultrue")
    public Result deleteBacBloodCultrue(@RequestBody BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.deleteBacBloodCultrue(bacBloodCultrue);
    }

    @ApiOperation("修改")
    @PostMapping("/updateBacBloodCultrue")
    public Result updateBacBloodCultrue(@RequestBody BacBloodCultrue bacBloodCultrue) {
        return bacBloodCultrueService.updateBacBloodCultrue(bacBloodCultrue);
    }

    @ApiOperation("血培养转种")
    @PostMapping("/bloodCultureTransplantation")
    public Result bloodCultureTransplantation(@RequestBody BloodCultureTransplantationParam input) {
        return bacBloodCultrueService.bloodCultureTransplantation(input);
    }

    @ApiOperation("发布72小时无菌培养结果")
    @PostMapping("/publish72NoGermReport")
    public Result publish72NoGermReport(@RequestBody BacBloodCultrue bacBloodCultrue) throws JsonProcessingException {
        SysUser sysUser = RedisUserManager.getUser();
        //清空掉之前发布的记录
        LambdaQueryWrapper<BacBloodCultrue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BacBloodCultrue::getRptGroup, bacBloodCultrue.getRptGroup())
                .eq(BacBloodCultrue::getSampleNo, bacBloodCultrue.getSampleNo())
                .eq(BacBloodCultrue::getSampleda, bacBloodCultrue.getSampleda())
                .eq(BacBloodCultrue::getDelFlag, 0);

        bacBloodCultrueService.saveOrUpdate(bacBloodCultrue, lambdaQueryWrapper);
        //调用接口，发布报告到his
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            for (String webUrl : collect) {
                /*微生物发送一级二级报告回传his*/
                SysParamParam sysp1 = new SysParamParam();
                sysp1.setParamCode("xtxxcs");
                sysp1.setField("wswfsyjejbghchis");
                List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                if (!r1.isEmpty()) {
                    if (r1.get(0).getValue().equals("1")) {
                        //更新细菌结果表状态
//                        LambdaUpdateWrapper<BacBloodCultrue> lambdaUpdateWrapper1 = new LambdaUpdateWrapper();
//                        lambdaUpdateWrapper1.eq(BacBloodCultrue::getRptGroup, bacBloodCultrue.getRptGroup())
//                                .eq(BacBloodCultrue::getSampleNo, bacBloodCultrue.getSampleNo())
//                                .eq(BacBloodCultrue::getSampleda, bacBloodCultrue.getSampleda())
//                                .eq(BacBloodCultrue::getDelFlag, 0)
//                                .set(BacBloodCultrue::getBacPublishStatus, 1);
//                        bacBloodCultrueService.update(lambdaUpdateWrapper1);
                        String releaseReport = webUrl + "/public/releaseWswReport";
                        List<Map> list = new ArrayList<>();
                        Map<String, Object> releaseReportMap = new HashMap<>();
                        HashMap<Object, Object> map1 = new HashMap<>();
                        map1.put("rptGroup", bacBloodCultrue.getRptGroup());
                        map1.put("sampleNo", bacBloodCultrue.getSampleNo());
                        map1.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bacBloodCultrue.getSampleda()));
                        list.add(map1);
                        releaseReportMap.put("orgId", sysUser.getOrgId());
                        //子报告
                        releaseReportMap.put("children", "1");
                        releaseReportMap.put("reportInfos", list);
                        releaseReportMap.put("username", sysUser.getUsername());
                        releaseReportMap.put("realname", sysUser.getRealname());
                        releaseReportMap.put("result72", "1");
                        String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                        //更新主表状态
                        LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper();
                        lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, bacBloodCultrue.getRptGroup())
                                .eq(LabMaininfo::getSampleNo, bacBloodCultrue.getSampleNo())
                                .eq(LabMaininfo::getSampleda, bacBloodCultrue.getSampleda())
                                .eq(LabMaininfo::getDelFlag, 0)
                                .isNull(LabMaininfo::getBacFlowNode)
                                .set(LabMaininfo::getBacFlowNode, bacBloodCultrue.getTestNodeNo());
                        labMaininfoService.update(lambdaUpdateWrapper);
                    }
                }
            }
        }
        return Result.succ(1, "发布成功", bacBloodCultrue);
    }
}
